import time
import unittest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait

class TestCase(unittest.TestCase):

    # 初始化浏览器驱动
    def setUp(self):
        # 指定浏览器
        self.driver = webdriver.Chrome()
        # 窗口最大化
        self.driver.maximize_window()
        # 打开网址
        self.driver.get('https://re.m.jd.com/page/homelike?ad_od=3&re_dcp=21Sm2D2ZOw&traffic_source=1004&bd_vid=114adabe7db1c028&cu=true&utm_source=haosou-search&utm_medium=cpc&utm_campaign=t_262767352_haosousearch&utm_term=64159740629_0_17b51dc4f2934ec3ac55a1921662f313')

    def tearDown(self):
        time.sleep(5)
        # 关闭浏览器
        self.driver.close()

    def test_01(self):
        # 搜索框
        self.driver.find_element(By.XPATH,'//*[@id="jd_search_contain"]/div/div/input').send_keys('智能手机')
        # 点击搜索按钮
        self.driver.find_element(By.XPATH,'//*[@id="jd_search_contain"]/div/div/a').click()
        #  窗口切换
        self.driver.switch_to.window(self.driver.window_handles[-1])
        # 智能等待
        WebDriverWait(self.driver, 20, 0.5)
        # 是否包含
        dy = self.driver.find_element(By.XPATH,'/html/body/div[6]/div[2]/div[1]/div/ul/li[1]/div/div[2]/a/div[2]').text
        self.assertIn('手机',dy)
        # 截屏保存
        self.driver.save_screenshot('jieguo.png')
        # 提取并输出前5个搜索结果的商品名称和价格信息
        for i in range(5):
            bt = self.driver.find_element(By.XPATH,'/html/body/div[6]/div[2]/div[1]/div/ul/li[1]/div/div[2]/a/div[2]').text
            jg = self.driver.find_element(By.XPATH,'/html/body/div[6]/div[2]/div[1]/div/ul/li[1]/div/div[2]/a/div[1]/span').text
            print(bt)
            print(jg)

    def test_02(self):
        # 点击登录按钮
        self.driver.find_element(By.CSS_SELECTOR,'#ttbar-login > a.link-login > span.style-red').click()